package com.wechat.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.admin.mapper.TokenBlacklistMapper;
import com.wechat.admin.model.entity.TokenBlacklist;
import com.wechat.admin.service.TokenBlacklistService;
import com.wechat.admin.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author dell
 * @description 针对表【token_blacklist】的数据库操作Service实现
 * @createDate 2024-12-20 09:54:51
 */
@Service
@Slf4j
public class TokenBlacklistServiceImpl extends ServiceImpl<TokenBlacklistMapper, TokenBlacklist>
        implements TokenBlacklistService {

    // 使用内存作为黑名单存储
    private final ConcurrentHashMap<String, Date> blacklist = new ConcurrentHashMap<>();

    /**
     * 将 Token 加入黑名单
     *
     * @param token JWT Token
     */
    public void addTokenToBlacklist(String token) {
        Date expiration = JwtUtil.validateToken(token).getExpiration();
        blacklist.put(token, expiration);
        log.info("黑名单中的token为{}",blacklist);
    }

    /**
     * 检查 Token 是否在黑名单中
     *
     * @param token JWT Token
     * @return true 表示 Token 已失效，false 表示 Token 有效
     */
    public boolean isTokenBlacklisted(String token) {
        return blacklist.containsKey(token);
    }

    /**
     * 定期任务：每小时执行一次
     */
    @Scheduled(cron = "0 0 * * * ?") // 每小时的第0分钟执行
    public void scheduleClearExpiredTokens() {
        clearExpiredTokens();
        log.info("已清理过期 Token，当前时间：{}", new Date());
    }

    /**
     * 定期清理已过期的 Token
     */
    public void clearExpiredTokens() {
        blacklist.entrySet().removeIf(entry -> entry.getValue().before(new Date()));
    }
}




